<template>
  <div>
    <Dropdown
      :dropMenuList="localeList"
      :selectedKeys="selectedKeys"
      :headText="getLocaleText"
      :showText="showText"
      @menuEvent="handleMenuEvent"
      iconClass="language"
    ></Dropdown>
  </div>
</template>

<script lang="ts" setup>
import { Dropdown, DropMenu } from '@/components/Dropdown'
import { useLocale } from '@/locales/useLocale';
import { localeList } from '@/settings/localeSetting';
import { computed, ref, unref, watchEffect } from 'vue';
import { LocaleType } from '/#/config';

const props = defineProps({
  /**
   * Whether to display text
   */
  showText: { type: Boolean, default: true },
  /**
   * Whether to refresh the interface when changing
   */
  reload: { type: Boolean, default: true },
});


const { changeLocale, getLocale } = useLocale();

const selectedKeys = ref<string[]>([]);

watchEffect(() => {
  selectedKeys.value = [unref(getLocale)];
});
const getLocaleText = computed(() => {
  const key = selectedKeys.value[0];
  if (!key) {
    return '';
  }
  return localeList.find((item) => item.event === key)?.text;
});

function handleMenuEvent(menu: DropMenu) {
  if (unref(getLocale) === menu.event) {
    return;
  }
  console.log(menu.event)
  toggleLocale(menu.event as string);
}

async function toggleLocale(lang: LocaleType | string) {
  await changeLocale(lang as LocaleType);
  selectedKeys.value = [lang as string];
  props.reload && location.reload();
}


</script>